﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace XL_ModbusRtu
{
    public class XLTCP : ICommunications
    {
        private string _ip;
        public string IP => _ip;
        private int _port;
        public int Port => _port;
        private int _index;
        public int Index => _index;
        public int Timeout { get; set; }
        private Socket _socket;
        public XLTCP(int index, string ip, int port, int timeout = 3000)
        {
            _ip = ip;
            _port = port;
            _index = index;
            Timeout = timeout;
        }

        public void Write(byte[] bytes) => _socket.Send(bytes);

        public byte[] Read()
        {
            byte[] bytes = new byte[256];
            int length = _socket.Receive(bytes, SocketFlags.None);
            return bytes.Take(length).ToArray();
        }

        public bool Open()
        {
            _socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
            _socket.ReceiveTimeout = 1000;
            _socket.SendTimeout = 1000;
            _socket.ReceiveBufferSize = 512;
            _socket.SendBufferSize = 512;
            _socket.Connect(IPAddress.Parse(_ip), _port);
            return true;
        }

        public void Close()
        {
            if (_socket != null)
            {
                _socket.Close();
            }
        }
    }
}
